package com.haredot.oss;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;

import java.io.*;

public class LocalOssClient extends AbstractOSSClient {

    private final String endPoint ;

    public LocalOssClient(String endPoint) {
        Assert.hasLength(endPoint, "endPoint值为空");
        Assert.isTrue(!endPoint.startsWith("http://") && !endPoint.startsWith("https://"),
                "endpoint值应该为一个本地磁盘路径、而非网络地址");
        this.endPoint = endPoint ;
    }

    @Override
    public PutObjectResult putObject(String bucketName, String key, InputStream input) throws OSSException, ClientException {
        File file = new File(this.endPoint + File.separator + bucketName, key) ;
        FileOutputStream fileOutputStream = null ;
        try {
            file.getParentFile().mkdirs(); // 进行构建
            fileOutputStream = new FileOutputStream(file);
            StreamUtils.copy(input, fileOutputStream);
            return null ;
        } catch (IOException e) {
            throw new OSSException("上传地址不存在");
        } finally {
            try {
               if (fileOutputStream!=null) fileOutputStream.close();
               if (fileOutputStream!=null) input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public PutObjectResult putObject(PutObjectRequest putObjectRequest) throws OSSException, ClientException {
        return this.putObject(putObjectRequest.getBucketName(), putObjectRequest.getKey(), putObjectRequest.getInputStream());
    }

    @Override
    public OSSObject getObject(GetObjectRequest getObjectRequest) throws OSSException, ClientException {
        OSSObject ossObject = new OSSObject();

        String bucketName = getObjectRequest.getBucketName();
        String key = getObjectRequest.getKey();

        ossObject.setBucketName(bucketName);
        ossObject.setKey(key);
        // 获取对应的流数据
        File file = new File(this.endPoint + File.separator + bucketName, key) ;
        try {
            ossObject.setObjectContent(new FileInputStream(file));
            return ossObject ;
        } catch (FileNotFoundException e) {
            throw new OSSException("下载的文件地址在磁盘不存在");
        }
    }
}
